<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Reserva_Model extends CI_Model {
    
    const TABLE_RESERVA     = 'reserva';
    const TABLE_CONTRATO    = 'contrato';
    const TABLE_CLIENTE     = 'cliente';
    const TABLE_STATUS      = 'status';
    const TABLE_BOLETO      = 'boleto';
    const TABLE_USUARIO     = 'usuario';
    const TABLE_PERFIL      = 'perfil';

    public $idreserva = '';
    public $idcontrato = ''; 
    public $title = ''; 
    public $dtinicial = ''; 
    public $dtfinal = '';
    public $descricao = '';
    
    function __construct($data = null) { 
        parent::__construct();
        if ($data) { 
            $this->_init($data); 
        }
    }
    function _init($data) { 
        if(is_object($data)){
            if (isset($data->idreserva)){ 
                $this->idreserva = $data->idreserva; 
            }else{
                $this->idreserva = null; 
            }
            $this->idreserva = $data->idreserva;
            $this->idcontrato = $data->idcontrato;  
            $this->title = $data->title;
            $this->dtinicial = $data->dtinicial;  
            $this->dtfinal = $data->dtfinal;
            $this->descricao = $data->descricao;
        }
        elseif(is_array($data)){ 
            if (isset($data['idusuario'])) {
                $this->idusuario = $data['idusuario']; 
            }else{
                $this->idusuario = null;
            }
            $this->idreserva = $data['idreserva'];
            $this->idcontrato = $data['idcontrato'];
            $this->title = $data['title']; 
            $this->dtinicial = $data['dtinicial']; 
            $this->dtfinal = $data['dtfinal'];
            $this->descricao = $data['descricao'];
        } 
    }
    function reservasVisita(){
        $query = $this->db->get_where(self::TABLE_RESERVA, array('status_idstatus'=>3));
        if ($query->num_rows() > 0 ) { 
            $reservas = $query->result();       
            return $reservas;
        }
    }
    function reservas(){
        if($this->session->userdata('perfil') != 'administrador'){
            $query = $this->db->get_where(self::TABLE_RESERVA, array('usuario_idusuario'=>$this->session->userdata('idusuario'),'status_idstatus !='=>1));                                  
            if ($query->num_rows() > 0 ) {
               $reservas = $query->result(); 
               return $reservas;
            }
        }else{
            $query = $this->db->get(self::TABLE_RESERVA);
            if ($query->num_rows() > 0 ) { 
                $reservas = $query->result();       
                return $reservas;
            }
        }
    }
    function reservaPorId($token){ 
        $query = $this->db->get_where(self::TABLE_RESERVA, array('token'=>$token));
        if ($query->num_rows() > 0 ) {      
            $token = $query->row();
            $this->_init($token);         
            return $this;
        }
        return false;
    }

    function agendamentoCliente($idusuario, $agendamento){        
        $this->db->select('*');
        $this->db->from(self::TABLE_RESERVA);
        $this->db->where('usuario_idusuario', $idusuario);
        $this->db->where('dtinicial', $agendamento);
        $this->db->where('cancelada !=', 1);
        $this->db->where('status_idstatus', 2);
        $query = $this->db->get();
        //return $query->result();
        if ($query->num_rows() > 0 ) { 
            return true;
        }else{
            return false;
        }
    }

    function todosAgendamentos(){        
        $this->db->select('*');
        $this->db->from(self::TABLE_RESERVA);
        $this->db->where('status_idstatus', 2);        
        $query = $this->db->get();
        return $query->result();        
    }

    function aptidaoCliente($idusuario){
        $query = $this->db->get_where(self::TABLE_CLIENTE, array('usuario_idusuario'=>$idusuario,'susp'=>1));                                  
            if ($query->num_rows() > 0 ) {
               $aptidao = $query->result(); 
               return $aptidao;
            }
    }
    function verificaDataReserva($data){  
       /* $this->db->select('dtfinal, dtinicial, dtreserva');
        $this->db->from(self::TABLE_RESERVA);
        $this->db->or_where(array('dtinicial'=>date('Y-m-d',strtotime($data . "-1 days")),'dtfinal'=>date('Y-m-d',strtotime($data . "+1 days"))));
        $this->db->or_where(array('dtinicial'=>date('Y-m-d',strtotime($data)),'dtfinal'=>date('Y-m-d',strtotime($data))));       
        $dtreserva = $this->db->get();
        return $dtreserva->result();
        $dtinicial = ;
        $dtfinal = ;  
        --> REMOVIDO PARA TRABALHAR O STATUS DE RESERVA LIVRE.*/
        /*
        $dtinicial = date('Y-m-d',strtotime($data));
        $dtfinal = date('Y-m-d',strtotime($data));
        $dtinicialN =  date('Y-m-d',strtotime($data . "-1 days"));
        $dtfinalP = date('Y-m-d',strtotime($data . "+1 days"));   
        $query = $this->db->query("SELECT dtfinal, dtinicial, dtreserva FROM reserva WHERE (status_idstatus != 1 AND dtinicial = '$dtinicialN')
            OR (status_idstatus != 1 AND dtfinal = '$dtfinalP') OR (status_idstatus != 1 AND dtinicial = '$dtinicial' OR dtfinal = '$dtfinal')");
        return $query->result();
        --> REMOVIDO PARA TRABALHAR DEIXANDO  A VERIFICAÇÃO DO STATUS DE RESERVA AGENDADO.*/
        $query = $this->db->get_where(self::TABLE_RESERVA, array('status_idstatus'=>3, 'dtinicial'=>date('Y-m-d',strtotime($data))));                                  
            return $query->result();      
    }

    function agendamentos($data){
        if(!empty($data)){
            /*$this->db->select('*');
            $this->db->from(self::TABLE_RESERVA);
            $this->db->where(array('dtinicial'=>date('Y-m-d',strtotime($data . "-1 days")),'dtfinal'=>date('Y-m-d',strtotime($data . "+1 days"))));
            $this->db->or_where(array('dtinicial'=>date('Y-m-d', strtotime($data)),'dtfinal'=>date('Y-m-d',strtotime($data))));  
            $this->db->where(array('dtreserva'=>NULL));
            $dtagendamento = $this->db->get();
            --> REMOVIDO PARA TRABALHAR O STATUS DE RESERVA LIVRE.*/
           
           /* $dtinicial = date('Y-m-d',strtotime($data));
            $dtfinal = date('Y-m-d',strtotime($data));
            $dtinicialN =  date('Y-m-d',strtotime($data . "-1 days"));
            $dtfinalP = date('Y-m-d',strtotime($data . "+1 days"));   
            $query = $this->db->query("SELECT dtfinal, dtinicial, dtreserva FROM reserva WHERE 
                (status_idstatus != 1 AND dtinicial = '$dtinicialN')
            OR  (status_idstatus != 1 AND dtfinal   = '$dtfinalP') 
            OR  (status_idstatus != 1 AND dtinicial = '$dtinicial') 
            OR  (status_idstatus != 1 AND dtfinal   = '$dtfinal') 
            AND dtreserva = NULL");
            return $query->result();
            -->-->* REMOVIDO PARA AGORA TRABALHAR SEM LIMITE DE AGENDAMENTOS POR DATA.*/
        }
        /*else{
            $dtagendamento = $this->db->get(self::TABLE_RESERVA);
        }
        return $dtagendamento->result();
        -->-->* REMOVIDO PARA AGORA TRABALHAR SEM LIMITE DE AGENDAMENTOS POR DATA.*/
    }

    function periodos($dtinicial,$dtfinal){
        if(!empty($dtinicial) && !empty($dtfinal)){
          /*  $this->db->select('*');
            $this->db->from(self::TABLE_RESERVA);
            $this->db->where("status_idstatus != 1"); 
            $this->db->where("`dtfinal` BETWEEN '$dtinicial' AND '$dtfinal'", NULL, FALSE);
            $this->db->or_where("`dtinicial` BETWEEN '$dtinicial' AND '$dtfinal'", NULL, FALSE);            
            $periodo = $this->db->get();
            return $periodo->result();
             --> REMOVIDO PARA AGORA TRABALHAR SEM LIMITE DE AGENDAMENTOS POR DATA.*/
        }
    }

    function clientePorReserva($token){ 
        $this->db->select('*');
        $this->db->from(self::TABLE_CLIENTE);
        $this->db->join(self::TABLE_RESERVA, 'reserva.usuario_idusuario = cliente.usuario_idusuario','inner');
        $this->db->join(self::TABLE_STATUS, 'reserva.status_idstatus = status.idstatus','inner');
        $this->db->where('token',$token);
        $cliente = $this->db->get();
        return $cliente->result();
    }

    function gerenciaReservas(){
        if($this->session->userdata('perfil') != 'cliente'){
            $this->db->select('*');
            $this->db->from(self::TABLE_CLIENTE);
            $this->db->join(self::TABLE_RESERVA, 'reserva.usuario_idusuario = cliente.usuario_idusuario','inner');
            $this->db->join(self::TABLE_STATUS, 'reserva.status_idstatus = status.idstatus','inner');
            $this->db->where("status_idstatus != 1");
            $this->db->order_by("idreserva", 'desc');
            $cliente = $this->db->get();
            return $cliente->result();
        }        
    }

    function gerenciaReservasAdmin(){
        if($this->session->userdata('perfil') != 'cliente'){
            $this->db->select('*');
            $this->db->from(self::TABLE_USUARIO);
            $this->db->join(self::TABLE_PERFIL, 'perfil.idperfil = usuario.perfil_idperfil','inner');
            $this->db->join(self::TABLE_RESERVA, 'reserva.usuario_idusuario = usuario.idusuario','inner');
            $this->db->join(self::TABLE_STATUS, 'reserva.status_idstatus = status.idstatus','inner');
            $this->db->where('sigla','adm');            
            $this->db->order_by("idreserva", 'desc');
            $cliente = $this->db->get();
            return $cliente->result();
        }        
    }

    function aprovaReserva($reserva){
        if($this->session->userdata('perfil') != 'cliente'){
            $dtreserva = array('dtreserva'=>date('Y-m-d', strtotime("now")),'status_idstatus'=>'3');
            $this->db->update(self::TABLE_RESERVA, $dtreserva, "idreserva = $reserva");
            $parcelaBol = array('baixa'=>1);
            $this->db->update(self::TABLE_BOLETO, $parcelaBol, array('reserva_idreserva'=>$reserva, 'nparcela'=>1));
            $this->db->update(self::TABLE_BOLETO, array('emitido'=>1), array('reserva_idreserva'=>$reserva, 'nparcela'=>2));
        }        
    }

    function liberaReserva($reserva){
        if($this->session->userdata('perfil') != 'cliente'){
            $dtreserva = array('dtreserva'=>NULL,'status_idstatus'=>'2');
            $this->db->update(self::TABLE_RESERVA, $dtreserva, "idreserva = $reserva");
            $parcelaBol = array('baixa'=>0);
            $this->db->update(self::TABLE_BOLETO, $parcelaBol, array('reserva_idreserva'=>$reserva));
        }        
    }

    function insere($reserva){  
        if($reserva['dtfinal'] < $reserva['dtinicial'] || $reserva['dtfinal'] == ""){
            $reserva['dtfinal'] = $reserva['dtinicial'];
        }
        $ano = date( 'Y', strtotime($reserva['dtinicial']));
        $contrato = $this->db->get_where(self::TABLE_CONTRATO, array('ano' => $ano));
        $contrato->row();
        $idcontrato = $contrato->result_object[0]->idcontrato;

        $fila = $this->db->get_where(self::TABLE_RESERVA, array('espera' =>0, 'cancelada'=>0, 'dtinicial'=>$reserva['dtinicial']));
        if ($fila->num_rows() > 0 ) { 
            $dados = array_merge($reserva, array('contrato_idcontrato'=>$idcontrato, 'espera'=>1));
        }
        else{
            $dados = array_merge($reserva, array('contrato_idcontrato'=>$idcontrato));
        }        
        $this->db->insert(self::TABLE_RESERVA, $dados);
        return $this->db->insert_id('idreserva');
    }
    function exclui($reserva){
        if($this->session->userdata('perfil') != 'cliente'){
            $this->db->update(self::TABLE_BOLETO, array('ativo_bol'=>0), "reserva_idreserva = $reserva");
            $this->db->update(self::TABLE_RESERVA, array('status_idstatus'=>1), "idreserva = $reserva");
            //$this->db->delete(self::TABLE_BOLETO, "reserva_idreserva = $reserva");
           // $this->db->delete(self::TABLE_RESERVA, "idreserva = $reserva");            
        }
    }
}